package com.hzsk.lisence.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

@Configuration
@EnableJpaRepositories(basePackages = "com.hzsk.lisence")
public class JpaConfiguration {

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Bean
    PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        prepareDatabase();
        return new PersistenceExceptionTranslationPostProcessor();
    }

    public void prepareDatabase() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String getmysql_url = String.format("jdbc:mysql://%s:%d/", "10.1.1.114", 3306);

            // 连接已经存在的数据库，如：mysql
            Connection connection = DriverManager.getConnection(getmysql_url, username, password);
            Statement statement = connection.createStatement();
            // 创建数据库
            statement.executeUpdate("create database if not exists  empower_management  default character set utf8");

            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
